import json
import wx
import requests
import time
from bs4 import BeautifulSoup


def getCity(type):
    global req
    headers = {
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 '
                      'Safari/537.36 '
    }
    try:
        req = requests.get(url='https://ncov.dxy.cn/ncovh5/view/pneumonia_risks?from=dxy&link=&share=&source=',
                           headers=headers)
    except Exception:
        wx.MessageBox('网络连接失败')
        exit(1)
    req.encoding = 'utf8'
    html = req.text
    soup = BeautifulSoup(html, "html.parser")
    soup = soup.find('script', id='getAreaStat')
    data = str(soup)
    data = data.replace('<script id="getAreaStat">try { window.getAreaStat = ', '')

    data = data.replace('}catch(e){}</script>', '')
    if type == 'city':
        CityName = {}
        ProvinceName = []
        CityData = json.loads(data)
        for item_i in CityData:
            cities = []
            if item_i['cities']:
                for item_ii in item_i['cities']:
                    cities.append(item_ii['cityName'])
            else:
                cities.append(item_i['provinceShortName'])
            ProvinceName.append(item_i['provinceShortName'])
            CityName[item_i['provinceShortName']] = cities
        return ProvinceName, CityName
    elif type == 'covid':
        return json.loads(data)


class CnCovid(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        ProvinceName, CityName = getCity('city')
        self.province_string = wx.StaticText(self, label='省份', pos=(50, 50))
        self.province_choose = wx.ComboBox(self, pos=(100, 50), size=(150, 25), choices=ProvinceName,
                                           style=wx.TE_READONLY)
        self.province_choose.Bind(wx.EVT_COMBOBOX, self.onChooseProvince)
        self.city_string = wx.StaticText(self, label='城市', pos=(270, 50))
        self.city_choose = wx.ComboBox(self, pos=(320, 50), size=(150, 25), choices=['请先选择省份'], style=wx.TE_READONLY)
        self.location_search = wx.Button(self, label='搜索', pos=(490, 45), size=(100, 35))
        self.location_search.Bind(wx.EVT_BUTTON, self.onClickSearch)
        self.attention = wx.StaticText(self, label='注意事项', pos=(50, 100))
        self.attention_output = wx.TextCtrl(self, pos=(50, 120), size=(540, 80), style=wx.TE_READONLY | wx.TE_MULTILINE)
        self.time_label = wx.StaticText(self, label='查询时间', pos=(50, 250))
        self.time_output = wx.TextCtrl(self, pos=(110, 250), size=(480, 25),
                                           style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入
        self.current_label = wx.StaticText(self, label='现存确诊', pos=(50, 290))
        self.current_output = wx.TextCtrl(self, pos=(110, 290), size=(205, 25),
                                          style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入
        self.total_label = wx.StaticText(self, label='累计确诊', pos=(325, 290))
        self.total_output = wx.TextCtrl(self, pos=(385, 290), size=(205, 25),
                                        style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入
        self.cured_label = wx.StaticText(self, label='累计治愈', pos=(50, 330))
        self.cured_output = wx.TextCtrl(self, pos=(110, 330), size=(205, 25),
                                        style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入
        self.dead_label = wx.StaticText(self, label='累计死亡', pos=(325, 330))
        self.dead_output = wx.TextCtrl(self, pos=(385, 330), size=(205, 25),
                                       style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入
        self.high_label = wx.StaticText(self, label='高风险', pos=(50, 370))
        self.high_output = wx.TextCtrl(self, pos=(110, 370), size=(205, 25),
                                        style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入
        self.mid_label = wx.StaticText(self, label='中风险', pos=(325, 370))
        self.mid_output = wx.TextCtrl(self, pos=(385, 370), size=(205, 25),
                                       style=wx.TE_MULTILINE | wx.TE_READONLY)  # 禁止手动输入

    def onClickSearch(self, event):
        Province = self.province_choose.GetValue()
        City = self.city_choose.GetValue()
        if Province == '':
            wx.MessageBox('请先选择省份和城市！')
            return
        data = getCity('covid')
        self.time_output.SetValue(time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime()))
        for item_i in data:
            if item_i['provinceShortName'] == Province and not item_i['cities']:
                self.current_output.SetValue(str(item_i['currentConfirmedCount']))
                self.total_output.SetValue(str(item_i['confirmedCount']))
                self.cured_output.SetValue(str(item_i['curedCount']))
                self.dead_output.SetValue(str(item_i['deadCount']))
                self.high_output.SetValue(str(item_i['highDangerCount']))
                self.mid_output.SetValue(str(item_i['midDangerCount']))
                if item_i['comment']:
                    wx.MessageBox(item_i['comment'])
                    self.attention_output.SetValue(item_i['comment'])
                else:
                    self.attention_output.SetValue('暂无')
                break
            elif item_i['provinceShortName'] == Province:
                for item_ii in item_i['cities']:
                    if item_ii['cityName'] == City:
                        self.current_output.SetValue(str(item_ii['currentConfirmedCount']))
                        self.total_output.SetValue(str(item_ii['confirmedCount']))
                        self.cured_output.SetValue(str(item_ii['curedCount']))
                        self.dead_output.SetValue(str(item_ii['deadCount']))
                        self.high_output.SetValue(str(item_ii['highDangerCount']))
                        self.mid_output.SetValue(str(item_ii['midDangerCount']))
                        if item_i['comment']:
                            wx.MessageBox(item_i['comment'])
                            self.attention_output.SetValue(item_i['comment'])
                        else:
                            self.attention_output.SetValue('暂无')
                        break
                break

    def onChooseProvince(self, event):
        ProvinceChoice = self.province_choose.GetValue()
        ProvinceName, CityName = getCity('city')
        self.city_choose.SetItems(CityName[ProvinceChoice])
        self.city_choose.SetValue(CityName[ProvinceChoice][0])